package com.third.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.corba.se.impl.resolver.SplitLocalResolverImpl;
import com.third.annotations.RequirePermission;
import com.third.entity.Perms;
import com.third.entity.Role;
import com.third.entity.User;
import com.third.result.ResponseResult;
import com.third.service.UserService;
import com.third.utils.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Component
//加入IOC容器
public class PermsInterceptor extends HandlerInterceptorAdapter {

    private static final Logger logger = LoggerFactory.getLogger(PermsInterceptor.class);

    @Resource
    private UserService userService;
    //在handler方法执行之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {



        logger.debug("拦截请求");

        //得到token
        String token = request.getHeader("authorization");

        //1.得到即将被访问的方法
        //如果是请求的handler中的方法
        if (handler instanceof HandlerMethod){
            logger.debug("获取被请求的方法");
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            //
            Method method = handlerMethod.getMethod();
            logger.debug("判断方法上是否有指定的注解");
            if (method.isAnnotationPresent(RequirePermission.class)){
                logger.debug("方法上有注解,得到注解对象,获取值");
                RequirePermission rp = method.getDeclaredAnnotation(RequirePermission.class);
                logger.debug("获取注解中得值");
                String perms = rp.value();
                logger.debug(perms);

                //通过当前用户的账号,查询出所有的权限进行对比
                String account = JwtUtil.getAccount(token);

                //调用service查询数据库数据
                User user = userService.findByAccount(account);
                //遍历当前用户的权限
                for (Role r:user.getRoles()
                     ) {
                    for (Perms p:r.getPerms()
                         ) {
                        if (p.getName().equals(perms)){
                            logger.debug("有权限放行");
                            return true;
                        }
                    }
                }
                //for循环正常结束,没权限
                logger.debug("无权限");
                ResponseResult<String> responseResult = new ResponseResult<>();
                responseResult.setCode(500);
                responseResult.setMessage("无权限");
                //设置响应头
                response.setContentType("application/json;charset=utf-8");
                ObjectMapper om = new ObjectMapper();
                //返回数据
                om.writeValue(response.getWriter(),responseResult);
                return false;
            }
        }

        return super.preHandle(request, response, handler);
    }
}
